package hongcheng.code_generator.database;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import hongcheng.code_generator.entity.JdbcTypeInformation;
import hongcheng.code_generator.entity.config.CodeGeneratorConfig;
import hongcheng.code_generator.entity.db.TableColumnMetadata;
import hongcheng.code_generator.entity.db.TableMetadata;
import hongcheng.code_generator.exception.CustomException;
import hongcheng.code_generator.utils.DbType2JavaTypeUtils;

/**
 * 	读取Oracle数据库表元数据类
 * */
public class DefaultOracleBMetadataReader  extends AbstractDBMetadataReader{
	/**
	 * 	构造函数
	 * */
	public DefaultOracleBMetadataReader(CodeGeneratorConfig config) {
		super(config);
	};
	

	/**
	 * 	获取数据库元数据
	 * */
	@Override
	public TableMetadata getDBMetadata()  {
		TableMetadata tableMetadata = new TableMetadata();
		try {
			// 获取数据库管理类
			DBManager dbManager = new DBManager(getUrl(),getUser(),getPassword());
			// 连接
			dbManager.connection();
			Connection connection = dbManager.getConnection();
			// 获取指定表的注释
			String sql = "SELECT COMMENTS FROM user_tab_comments WHERE TABLE_NAME = '{}'";
			sql = StrUtil.format(sql, getTableName());
			ResultSet resultSet = dbManager.executeQuery(sql);
			while(resultSet.next()) {
				// 设置表注释
				tableMetadata.setTableComment(StrUtil.isBlank(resultSet.getString(1))?"":resultSet.getString(1));
			}
			// 设置表名
			tableMetadata.setTableName(getTableName());
			// 获取表主键，如果有多个主键，默认取最后一个
			DatabaseMetaData metaData = connection.getMetaData();
			ResultSet primaryKeys = metaData.getPrimaryKeys(null, getUser(), getTableName().toUpperCase());
			TableColumnMetadata primaryKey = new TableColumnMetadata();
			while(primaryKeys.next()) {
				primaryKey.setColumnName(primaryKeys.getString(4));
				primaryKey.setIsPrimaryKey(true);
			}
			tableMetadata.setPrimaryKey(primaryKey);
			// 查询表字段,列名、列类型、列注释
			sql = "SELECT tabcol.COLUMN_NAME,tabcol.DATA_TYPE,colcom.COMMENTS FROM user_tab_columns tabcol INNER JOIN user_col_comments colcom ON tabcol.COLUMN_NAME = colcom.COLUMN_NAME AND colcom.TABLE_NAME = '{}' WHERE tabcol.TABLE_NAME = '{}'";
			sql = StrUtil.format(sql, getTableName(), getTableName());
			ResultSet resultSet2 = dbManager.executeQuery(sql);
			
			List<TableColumnMetadata> tableColumnList = new ArrayList<TableColumnMetadata>();
			TableColumnMetadata tableColumn = null;
			
			while(resultSet2.next()) {
				tableColumn = new TableColumnMetadata();
				tableColumn.setColumnComment(StrUtil.isBlank(resultSet2.getString(3))?"":resultSet2.getString(3));
				tableColumn.setColumnName(resultSet2.getString(1));
				JdbcTypeInformation jdbcTypeInformation = DbType2JavaTypeUtils.getJdbcTypeInformation(resultSet2.getString(2));
				tableColumn.setJavaClassName(jdbcTypeInformation.getJavaClassFullName());
				tableColumn.setJavaType(jdbcTypeInformation.getJavaClassSimpleName());
				tableColumn.setJdbcType(jdbcTypeInformation.getMybatisJdbcType());
				if(tableColumn.getColumnName().equals(primaryKey.getColumnName())) {
					tableColumn.setIsPrimaryKey(true);
					primaryKey.setJavaClassName(jdbcTypeInformation.getJavaClassFullName());
					primaryKey.setJavaType(jdbcTypeInformation.getJavaClassSimpleName());
					primaryKey.setJdbcType(jdbcTypeInformation.getMybatisJdbcType());
				}else {
					tableColumn.setIsPrimaryKey(false);
				}
				tableColumnList.add(tableColumn);
			}
			tableMetadata.setTableColumnList(tableColumnList);
			dbManager.close();
		} catch (Exception e) {
			CustomException exception = new CustomException("获取表元数据异常");
			exception.addSuppressed(e);
			throw exception;
		}
		return tableMetadata;
	}
	
}
